// utils/breadcrumb.js

export function generateBreadcrumb(route, routesConfig) {
    // 初始化面包屑数组
    let breadcrumbPaths = [];
  
    // 查找匹配的路由记录
    const matched = route.matched.filter(record => record.meta && record.meta.title);
  
    const findRouteConfig = (path, configArray, parentPath = '') => {
      for (const config of configArray) {
        const fullPath = parentPath ? `${parentPath}/${config.path}` : config.path;
        if (config.path === path || fullPath === path) {
          return { ...config, path: fullPath };
        }
        if (config.children) {
          const childMatch = findRouteConfig(path, config.children, fullPath);
          if (childMatch) {
            return childMatch;
          }
        }
      }
      return null;
    };
  
    const buildBreadcrumb = (matchedRecord, routesConfig) => {
      const configMatch = findRouteConfig(matchedRecord.path, routesConfig);
  
      if (configMatch) {
        // 如果有父级路径，则递归添加父级路径的面包屑
        if (configMatch.parentPath) {
          const parentMatch = findRouteConfig(configMatch.parentPath, routesConfig);
          if (parentMatch && parentMatch.meta && parentMatch.meta.title) {
            breadcrumbPaths.push({
              path: parentMatch.path,
              meta: { title: parentMatch.meta.title }
            });
          }
        }
  
        if (configMatch.meta && configMatch.meta.title) {
          breadcrumbPaths.push({
            path: configMatch.path,
            meta: { title: configMatch.meta.title }
          });
        }
      } else if (matchedRecord.meta && matchedRecord.meta.title) { // 如果没有找到配置项但有meta信息，则直接使用
        breadcrumbPaths.push({
          path: matchedRecord.path,
          meta: { title: matchedRecord.meta.title }
        });
      }
    };
  
    matched.forEach((record) => {
      buildBreadcrumb(record, routesConfig);
    });
  
    // 如果是首页，确保至少有一个面包屑
    if (route.path === '/admin' && !breadcrumbPaths.length) {
      const homeMatch = findRouteConfig('/admin', routesConfig);
      if (homeMatch && homeMatch.meta && homeMatch.meta.title) {
        breadcrumbPaths.push({
          path: homeMatch.path,
          meta: { title: homeMatch.meta.title }
        });
      }
    }
  
    return breadcrumbPaths;
  }